<template>
  <div class="drafts-page">
    <NavBar />
    
    <div class="main-content">
      <div class="container">
        <div class="page-header">
          <h1 class="page-title">草稿箱</h1>
          <p class="page-subtitle">管理您的草稿文章</p>
        </div>

        <!-- 草稿列表 -->
        <div class="drafts-container">
          <div v-if="postsStore.loading" class="loading">
            <el-skeleton :rows="3" animated />
          </div>
          
          <div v-else-if="drafts.length === 0" class="empty-state">
            <el-empty description="暂无草稿">
              <el-button type="primary" @click="$router.push('/write')">
                写第一篇文章
              </el-button>
            </el-empty>
          </div>
          
          <div v-else class="drafts-list">
            <div 
              v-for="draft in drafts" 
              :key="draft.id" 
              class="draft-card"
              @click="$router.push(`/edit/${draft.id}`)"
            >
              <!-- 左侧图片 -->
              <div class="draft-image" v-if="draft.cover_image">
                <img 
                  :src="draft.cover_image" 
                  :alt="draft.title || '草稿'"
                  loading="lazy"
                />
              </div>
              
              <!-- 中间内容 -->
              <div class="draft-content">
                <h3 class="draft-title">{{ draft.title || '无标题' }}</h3>
                <p class="draft-excerpt">{{ draft.excerpt || '暂无摘要' }}</p>
                <div class="draft-meta">
                  <span class="draft-date">
                    {{ formatDate(draft.updated_at || draft.created_at) }}
                  </span>
                  <span class="draft-status">草稿</span>
                </div>
              </div>
              
              <!-- 右侧操作 -->
              <div class="draft-actions">
                <el-button 
                  size="small" 
                  @click.stop="editDraft(draft.id)"
                  type="primary"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  @click.stop="deleteDraft(draft.id)"
                  type="danger"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { usePostsStore } from '@/stores/posts'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import NavBar from '@/components/NavBar.vue'
import Footer from '@/components/Footer.vue'
import type { Post } from '@/types'

const router = useRouter()
const postsStore = usePostsStore()
const userStore = useUserStore()

const drafts = ref<Post[]>([])

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const loadDrafts = async () => {
  try {
    // 后端已经过滤了当前用户的草稿
    await postsStore.fetchPosts({ published_only: false })
    drafts.value = postsStore.posts.filter(post => !post.is_published)
    console.log('📝 草稿箱加载完成，当前用户草稿数量:', drafts.value.length)
  } catch (error) {
    console.error('加载草稿失败:', error)
    ElMessage.error('加载草稿失败')
  }
}

const editDraft = (id: string) => {
  router.push(`/edit/${id}`)
}

const deleteDraft = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个草稿吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    await postsStore.deletePost(id)
    ElMessage.success('草稿删除成功')
    loadDrafts() // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除草稿失败:', error)
      ElMessage.error('删除草稿失败')
    }
  }
}

onMounted(() => {
  loadDrafts()
})

// 当页面被激活时（从其他页面返回），重新加载草稿
onActivated(() => {
  loadDrafts()
})
</script>

<style scoped>
.drafts-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
  background: #f5f7fa;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 3rem;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #333;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  font-size: 1.125rem;
  color: #666;
}

.drafts-container {
  background: white;
  border-radius: 16px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.loading {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.empty-state {
  text-align: center;
  padding: 4rem 0;
}

.drafts-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.draft-card {
  display: flex;
  align-items: center;
  padding: 1.25rem;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 1.25rem;
  position: relative;
}

.draft-card:hover {
  border-color: #d4e8ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.08);
}

.draft-image {
  width: 140px;
  height: 100px;
  flex-shrink: 0;
  border-radius: 10px;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.draft-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.draft-content {
  flex: 1;
  min-width: 0;
}

.draft-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 0.5rem 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.draft-excerpt {
  color: #666;
  margin: 0 0 0.75rem 0;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-size: 0.875rem;
}

.draft-meta {
  display: flex;
  align-items: center;
  gap: 1rem;
  font-size: 0.8125rem;
  color: #8c8c8c;
}

.draft-status {
  background: #fff1f0;
  color: #cf1322;
  padding: 3px 10px;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
  border: 1px solid #ffccc7;
}

.draft-actions {
  display: flex;
  gap: 0.5rem;
  flex-shrink: 0;
}

.draft-actions .el-button {
  border-radius: 8px;
  font-weight: 500;
  padding: 8px 16px;
}

.draft-actions .el-button--primary {
  background: #1890ff;
  border-color: #1890ff;
}

.draft-actions .el-button--primary:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

.draft-actions .el-button--danger {
  background: #fff;
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.draft-actions .el-button--danger:hover {
  background: #fff1f0;
  border-color: #ff7875;
  color: #ff7875;
}

@media (max-width: 768px) {
  .draft-card {
    flex-direction: column;
    align-items: stretch;
    gap: 1rem;
  }
  
  .draft-content {
    margin-right: 0;
  }
  
  .draft-actions {
    justify-content: center;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .container {
    padding: 0 15px;
  }
}
</style>
